package com.jumi.microservice.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.core.web.page.TableDataInfo;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.controller.api.JmLevelUpController;
import com.jumi.microservice.dto.reponse.IdentityAuthenticationReponse;
import com.jumi.microservice.dto.request.IdentityAuthenticationQueryRequest;
import com.jumi.microservice.entity.JmIdentityAuthentication;
import com.jumi.microservice.entity.JmIdentityAuthenticationLog;
import com.jumi.microservice.entity.JmUser;
import com.jumi.microservice.enums.CheckStatus;
import com.jumi.microservice.service.IJmIdentityAuthenticationLogService;
import com.jumi.microservice.service.IJmIdentityAuthenticationService;
import com.jumi.microservice.service.IJmUserService;
import com.jumi.microservice.service.PageService;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色认证表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-07-31
 */
@RestController
@RequestMapping("/jm-identity-authentication")
@Transactional
@Api(value = "角色认证", tags = {"角色认证"})
public class JmIdentityAuthenticationController extends JmLevelUpController {

    @Autowired
    IJmIdentityAuthenticationService service;

    @Autowired
    IJmIdentityAuthenticationLogService logService;

    @Autowired
    IJmUserService userService;

    @PostMapping("/getInfo")
    @ApiOperation("角色认证分页")
    public TableDataInfo<IdentityAuthenticationReponse> getInfo(IdentityAuthenticationQueryRequest request,
                                                                Integer size, Integer current) {

        Page page = new Page(current, size);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, request);
        wrapper.orderByDesc("create_time");
        page = service.getPage(page, wrapper);
        return PageService.getDataTableInfo(page);
    }

    @PostMapping("/update")
    @ApiOperation("角色认证驳回/审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authId", value = "申请记录ID", required = true),
            @ApiImplicitParam(name = "remark", value = "审核原因"),
            @ApiImplicitParam(name = "status", value = "审核状态;待审核(0),已通过(1),未通过(2),未申请(3)", required = true)
    })
    @Transactional
    public ResponseResult update(Integer authId, String remark, CheckStatus status) {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();
        JmIdentityAuthentication byId = service.getById(authId);
        Integer uid = byId.getUid();
        JmUser user = userService.getById(uid);

        if (ObjectUtil.isNull(byId)) return ResponseResult.error("未查询到相关记录!");

        if (byId.getStatus().equals(CheckStatus.未通过)) {
            return ResponseResult.error("未通过记录，不允许操作!");
        }

        byId.setStatus(status);

        byId.setUpdateTime(LocalDateTime.now());
        byId.setRemark(remark);
        byId.setAdminId(adminId);
        byId.setAdminName(adminName);

        JmIdentityAuthenticationLog log = new JmIdentityAuthenticationLog();
        BeanUtils.copyProperties(byId, log);
        logService.save(log);

        Boolean Bool = service.updateById(byId);
        // 用户等级变动
        List<JmUser> users = new ArrayList<>();
        users.add(user);
        upgradeUserLevel(users, status);

        return ResponseResult.success(Bool);
    }

    /**
     * 用户等级变动
     *
     * @param users
     * @param status
     * @return
     */
    private boolean upgradeUserLevel(List<JmUser> users, CheckStatus status) {
        for (JmUser user : users) {
            // 若用户等级为1=团购用户,且本次审批通过status=1,则用户升级
            if (user.getLevel().getValue() == 1 && status.getValue() == 1) {
                this.levelUp(2, user.getId());
            }
        }
        return true;
    }

    @PostMapping("/batchUpdate")
    @ApiOperation("角色认证批量驳回/审核")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "ids", name = "申请记录ID集合", required = true),
            @ApiImplicitParam(value = "remark", name = "审核原因"),
            @ApiImplicitParam(value = "status", name = "审核状态;待审核(0),已通过(1),未通过(2),未申请(3)", required = true)
    })
    @Transactional
    public ResponseResult batchUpdate(String[] ids, String remark, CheckStatus status) {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        List<JmIdentityAuthentication> list = service.list(wrapper);
        List<JmIdentityAuthenticationLog> logs = new ArrayList<>();

        if (list.size() == 0) return ResponseResult.error("未查询到相关记录！");
        final JmIdentityAuthentication ja = list.get(0);

        List<Integer> uIds = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            uIds.add(list.get(0).getUid());
            if (ja.getStatus() != list.get(i).getStatus()) {
                return ResponseResult.error("所选记录存在不同审核阶段，请检查！");
            }
        }
        ja.setRemark(remark);
        CheckStatus checkStatus = ja.getStatus();
        if (checkStatus.equals(CheckStatus.未通过)) {
            return ResponseResult.error("未通过记录，不允许操作!");
        }

        ja.setStatus(status);

        list.stream().forEach(i -> {
            i.setRemark(ja.getRemark());
            i.setStatus(ja.getStatus());
            i.setUpdateTime(LocalDateTime.now());
            i.setAdminId(adminId);
            i.setAdminName(adminName);
            JmIdentityAuthenticationLog log = new JmIdentityAuthenticationLog();
            BeanUtils.copyProperties(i, log);
            logs.add(log);
        });
        logService.saveBatch(logs);
        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.in("id", uIds);
        List<JmUser> users = userService.list(wrapper);
        this.upgradeUserLevel(users, status);

        return ResponseResult.success(service.updateBatchById(list));
    }

}
